package logic

import (
	"context"
	"fmt"
	"user-sys/models"
	"user-sys/pkg"

	"user-sys/user_rpc/internal/svc"
	"user-sys/user_rpc/user_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RestLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RestLogic {
	return &RestLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RestLogic) Rest(in *user_rpc.RestRequest) (*user_rpc.RestResponse, error) {
	// todo: add your logic here and delete this line
	Image_key := fmt.Sprintf("account form InageCaptcha:%s", in.Account)
	Sms_key := fmt.Sprintf("phone from SmsCaptcha:%s", in.Phone)
	image_code, _ := models.RDB.Get(models.Ctx, Image_key).Result()
	Sms_code, _ := models.RDB.Get(models.Ctx, Sms_key).Result()
	if in.ImageCode != image_code {
		return &user_rpc.RestResponse{}, fmt.Errorf("图形验证码错误")
	}
	if in.SmsCode != Sms_code {
		return &user_rpc.RestResponse{}, fmt.Errorf("短信验证码错误")
	}
	var user models.User
	if err := models.DB.Where("user_account = ?", in.Account).Limit(1).Find(&user).Error; err != nil {
		return &user_rpc.RestResponse{}, fmt.Errorf("服务器繁忙")
	}
	if user.ID != 0 {
		return &user_rpc.RestResponse{}, fmt.Errorf("账号已存在")
	}
	user.UserPassword = pkg.MD5(in.Password)
	user.UserPhone = in.Phone
	user.UserAccount = in.Account
	if err := models.DB.Create(&user).Error; err != nil {
		return &user_rpc.RestResponse{}, fmt.Errorf("服务器繁忙")
	}
	if err := models.DB.Where("user_account = ?", in.Account).Limit(1).Find(&user).Error; err != nil {
		return &user_rpc.RestResponse{}, fmt.Errorf("服务器繁忙")
	}
	return &user_rpc.RestResponse{
		Id: int64(user.ID),
	}, nil
}
